package com.dreammore.framework.common.utils;

import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.type.JavaType;



public class JsonUtil {

	//public final static ObjectMapper mapper = new ObjectMapper();

	public static String bean2Json(Object object) throws Exception {
		ObjectMapper mapper = new ObjectMapper();
		//StringWriter sw = new StringWriter();
		//JsonGenerator gen = new JsonFactory().createJsonGenerator(sw);
		//mapper.writeValue(sw, object);
		//gen.close();
		//return sw.toString();
		return mapper.writeValueAsString(object);
	}

	public static <T> T json2Bean(String jsonString, Class<T> objectClass) throws Exception {
		ObjectMapper mapper = new ObjectMapper();
		mapper.enableDefaultTyping();
		return mapper.readValue(jsonString, objectClass);
	}
	
	public static <T> Collection<T> json2List(String jsonArrayString, Class<?> collectionClass, Class<T> objectClass) throws Exception {
		ObjectMapper mapper = new ObjectMapper();
		JavaType javaType = mapper.getTypeFactory().constructParametricType(collectionClass, objectClass);
		return mapper.readValue(jsonArrayString, javaType); 
	}
	
	public static <K, V> Map<K, V> json2Map(String jsonMapString, Class<K> kClass, Class<V> vClass) throws Exception {
		ObjectMapper mapper = new ObjectMapper();
		JavaType javaType = mapper.getTypeFactory().constructParametricType(HashMap.class, vClass);
		return mapper.readValue(jsonMapString, javaType); 
	}

	

}